package com.eoekun.dashboard.model;

import java.io.Serializable;
import com.alibaba.fastjson.JSON;

/**
 * gps 通用返回结果
 * 
 * @ClassName: result
 * @author chenkun
 * @date 2016年11月23日 上午11:19:10
 * @param <T>
 */
public class Result<T> implements Serializable {
    /**
     * @Fields serialVersionUID
     */
    private static final long serialVersionUID = 6344048315960893100L;
    /** 是否成功 */
    private boolean success = false;
    /** 返回内容 */
    private T data;
    /** 错误代码,0为成功,其他均为失败 */
    private String code = ResultCode.SYS_EXCEPTION.getCode();
    /** 错误描述 */
    private String message;

    public Result() {
        super();
    }

    public Result(T data) {
        super();
        this.success = true;
        this.code = ResultCode.SUCCESS.getCode();
        this.message = ResultCode.SUCCESS.getMsg();
        this.data = data;
    }

    public Result(Result<?> result) {
        super();
        this.success = false;
        this.code = result.getCode();
        this.message = result.getMessage();
    }

    public Result(ResultCode resultCode) {
        super();
        this.success = resultCode.getCode().equals(ResultCode.SUCCESS.getCode());
        this.code = resultCode.getCode();
        this.message = resultCode.getMsg();
    }

    public Result(String code, String message) {
        super();
        this.success = ResultCode.SUCCESS.getCode().equals(code);
        this.code = code;
        this.message = message;
    }

    public Result(ResultCode resultCode, String message) {
        super();
        this.success = ResultCode.SUCCESS.equals(resultCode);
        this.code = resultCode.getCode();
        this.message = message;
    }

    public Result<T> setResultCode(Result<T> result, ResultCode resultCode) {
        result.setCode(resultCode.getCode());
        result.setMessage(resultCode.getMsg());
        return result;
    }

    public static <T> Result<T> ofSuccess() {
        return ofSuccess(null);
    }

    public static <T> Result<T> ofSuccess(T data) {
        Result<T> result = new Result<>(ResultCode.SUCCESS);
        result.setData(data);
        return result;
    }

    public void setFail(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        if (success) {
            this.code = ResultCode.SUCCESS.getCode();
        }
        this.success = success;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
